package com.swak.frame.ratelimit.event;

import java.math.BigDecimal;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.swak.frame.ump.EventInfo;
import com.swak.frame.ump.adapter.AlarmEventAdapter;

@Component("rateLimitAlarmEvent")
public class RateLimitAlarmEvent implements RateAlarmEvent {

	@Autowired
	private AlarmEventAdapter alarmEventAdapter;

	@Override
	public void event(RateLimitEventInfo event) {
		EventInfo.Builder builder = new EventInfo.Builder();
		String name = StringUtils.firstNonEmpty(event.getName(),"接口");
		String info = "[{}]:[{}-{}] frequent access triggers current limiting! config:[rate={},qps={}]";
		Object[] args = new Object[] {event.getLimitType(),name,event.getResource(), event.getRate(),event.getRate()};
		if (event.isDynamic()) {
			info = "[{}]:[{}-{}]  frequent access triggers current limiting! config:[rate={},qps={},instances={}]";
			BigDecimal qps = new BigDecimal(event.getRate()).multiply(new BigDecimal(event.getInstances()));
			args = new Object[] { event.getLimitType(),name,event.getResource(), event.getRate(), qps.intValue(),event.getInstances()};
		}
		builder.info(info).bizTag("ratelimit").args(args);
		alarmEventAdapter.event(builder.build());
	}
}
